/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p3as.cliente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;


public class SceneController implements ActionListener{

    private AnimationController animationController;
    private Principal principal;
    private Renderer renderer;
    private MouseController mouseController;
    private PhaseLoader phaseConnection;
    private Score score;
    private Scene scene;

    SceneController(Principal principal) {
        this.principal = principal; 
        
        phaseConnection = new PhaseConnection();
        scene = (Scene) phaseConnection.loadPhase();
        
        score = new Score();
        animationController = new AnimationController(scene, score, principal);
        mouseController = new MouseController(animationController);
        Boundary boundary = new Boundary(399,399);
        scene.addChild(boundary);
        renderer = new Renderer(scene, principal);
        
    }

    void execute() {       
        principal.getCanvas().addMouseListener(mouseController);
        
        for(int i = 0; i < scene.getSize(); i++){
            if(scene.getChild(i) instanceof Brick){
                scene.getChild(i).setScore(score);
            }
        }
       
        animationController.start();
        renderer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if("Finish".equals(e.getActionCommand())){  
            ScoreConnection scoreConnection = new ScoreConnection();
            principal.paintRanking(scoreConnection.saveScore(principal.getUserText().getText(), Integer.valueOf(principal.getScoreText().getText())));
        }
        else if("Next".equals(e.getActionCommand())){
            PhaseConnection phaseConnection = new PhaseConnection();
            Scene auxScene = (Scene) phaseConnection.loadPhase();
            
            ArrayList<Ball> ballList = new ArrayList();
            for(int i = 0; i < auxScene.getSize(); i++){
                if(auxScene.getChild(i) instanceof Ball){
                    ballList.add((Ball) auxScene.getChild(i));
                }
            }
            
            animationController.setScene(auxScene);
            renderer.setScene(auxScene);
            animationController.setBallList(ballList);
        }
    }
    
}
